﻿using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Charades.Web.Server.Room;
using Charades.Web.Server.User;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace Charades.Web.Server.GenericManagers
{
	public class ConnectionManager
	{
		private UserHandler _userHandler;
		private RoomHandler _roomHandler;
		private object _locker;

		public ConnectionManager(UserHandler userHandler, RoomHandler roomHandler, object locker)
		{
			_userHandler = userHandler;
			_roomHandler = roomHandler;
			_locker = locker;
		}

		public void OnConnected(string connectionId)
		{
		}

		public void OnReconnected(string connectionId)
		{
			// On reconnect, force the user to refresh
			OnDisconnected(connectionId);
		}

		/// <summary>
		/// On disconnect we need to remove the ship from our list of ships within the gameHandler.
		/// This also means we need to notify clients that the ship has been removed.
		/// </summary>
		public void OnDisconnected(string connectionId)
		{
			try
			{
				if (_userHandler.UserExists(connectionId))
				{
					var user = _userHandler.GetUser(connectionId);
					OnDisconnected(user);
				}
			}
			catch (Exception e)
			{
				////ErrorLog.Instance.Log(e);
			}
		}

		public void OnDisconnected(User.User user)
		{
			try
			{
				_userHandler.RemoveUser(user.ConnectionId);
				_roomHandler.RemoveUser(user.ConnectionId);
			}
			catch (Exception e)
			{
				////ErrorLog.Instance.Log(e);
			}
		}
	}
}